package networks;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIP, int serverPort) throws IOException {
        socket = new Socket(serverIP, serverPort);
    }

    public void start(){
        Scanner scanner = new Scanner(System.in);

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream= socket.getOutputStream();
            Scanner reader = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream)){

            while(true){
                // 1. 从控制台读取输入信息
                System.out.println("请输入要传输的内容:");
                String request = scanner.next();
                // 2. 将请求发送给服务器
                // 这里只是把数据发到数据缓冲区，并没有真的发送出去
                // 这里默认约定了读取一次数据均以 \n 作为结束符
                writer.println(request);
                // 为了真的发送出去，需要刷新缓冲区
                writer.flush();
                // 3. 接收响应
                String response = reader.next();
                // 4. 打印信息
                System.out.println(response);
            }

        }catch (IOException e) {
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
